# coding=utf-8
# 生成汽车充当障碍物,坐标对应地图town07
import glob
import os
import sys

# ==============================================================================
# -- Find CARLA module ---------------------------------------------------------
# ==============================================================================

try:
    sys.path.append(
        glob.glob(
            '../carla/dist/carla-*%d.%d-%s.egg'
            % (
                sys.version_info.major,
                sys.version_info.minor,
                'win-amd64' if os.name == 'nt' else 'linux-x86_64',
            )
        )[0]
    )
except IndexError:
    pass

# ==============================================================================
# -- Add PythonAPI for release mode --------------------------------------------
# ==============================================================================
try:
    sys.path.append(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/carla'
    )
except IndexError:
    pass


import carla
import random
import logging
import time

logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)

# Connect to the client and retrieve the world object
client = carla.Client('127.0.0.1', 2000)
# 设置等待的最大时间
client.set_timeout(10.0)
actors_list = []
try:
    # 获取世界对象
    world = client.get_world()

    # 设置同步模式,carla服务器默认运行在异步模式,由于我们需要在脚本中运行一个AI,所以需要使用异步模式.
    init_setting = world.get_settings()
    settings = world.get_settings()

    # 从蓝图中选择车辆
    vehicle_blueprints = world.get_blueprint_library().find('vehicle.audi.tt')
    vehicle_blueprints.set_attribute('color', '255,255,255')
    # 选择生成车辆的地点
    spawn_points = []
    # 路障-终点封路
    spawn_point_1 = carla.Transform(
        carla.Location(x=-197.405151, y=-169.926147, z=0.5),
        carla.Rotation(pitch=0.061376, yaw=177.044647, roll=0.000000),
    )
    spawn_point_2 = carla.Transform(
        carla.Location(x=-202.246246, y=-169.674194, z=0.5),
        carla.Rotation(pitch=0.068978, yaw=177.106201, roll=-0.000061),
    )
    # 路障-岔路封路
    spawn_point_3 = carla.Transform(
        carla.Location(x=-3.540427, y=-230.665894, z=0.5),
        carla.Rotation(pitch=0.071840, yaw=-178.888580, roll=-0.000000),
    )
    spawn_point_4 = carla.Transform(
        carla.Location(x=0.322178, y=-230.590683, z=0.5),
        carla.Rotation(pitch=0.070173, yaw=-178.882889, roll=0.000000),
    )
    # 路障-路中间
    spawn_point_5 = carla.Transform(
        carla.Location(x=51.989849, y=-151.439026, z=10),
        carla.Rotation(pitch=-4.630151, yaw=-118.327721, roll=-0.221711),
    )
    spawn_point_6 = carla.Transform(
        carla.Location(x=-69.841507, y=-218.079666, z=5.6),
        carla.Rotation(pitch=4.358603, yaw=116.034592, roll=-0.835693),
    )
    spawn_point_7 = carla.Transform(
        carla.Location(x=-165.717010, y=-243.195557, z=1.0),
        carla.Rotation(pitch=5.109213, yaw=2.341084, roll=-0.608551),
    )

    spawn_points.append(spawn_point_1)
    spawn_points.append(spawn_point_2)
    spawn_points.append(spawn_point_3)
    spawn_points.append(spawn_point_4)
    spawn_points.append(spawn_point_5)
    spawn_points.append(spawn_point_6)
    spawn_points.append(spawn_point_7)

    num_spawn_points = len(spawn_points)
    print(num_spawn_points)

    # 生成车辆
    for i in range(num_spawn_points):
        if i < 4:
            vehicle_blueprints = world.get_blueprint_library().find('vehicle.audi.a2')
        else:
            vehicle_blueprints = world.get_blueprint_library().find('vehicle.audi.tt')
        ego_spawn_point = spawn_points[i]
        ego_vehicleActor = world.spawn_actor(vehicle_blueprints, ego_spawn_point)
        print("Car ID %d is created!!") % (ego_vehicleActor.id)
        actors_list.append(ego_vehicleActor)

    # 服务器等待客户端创建完毕后更新
    while True:
        time.sleep(0.01)
        world.tick()

except KeyboardInterrupt:
    pass

finally:
    # 摧毁已经创建的车辆
    print('\ndestroying %d vehicles' % len(actors_list))
    client.apply_batch([carla.command.DestroyActor(x) for x in actors_list])

    # stop walker controllers (list is [controller, actor, controller, actor ...])

    time.sleep(0.5)
    print('\ndone.')
